package com.zys.el.time.service.lambda_like.schedule;

import com.zys.el.time.constants.RedisConstants;
import com.zys.el.time.entity.ThinkingLikeCount;
import com.zys.el.time.mapper.ThinkingLikeCountMapper;
import com.zys.el.time.mapper.ThinkingLikeMapper;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;

@Component
public class LambdaLikeScheduler {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private ThinkingLikeMapper thinkingLikeMapper;
    @Resource
    private ThinkingLikeCountMapper thinkingLikeCountMapper;

    /**
     * 定时更新点赞数量表
     */
    @Scheduled(cron = "0 0 3 1/1 * ?")
    public void updateLikeCount() {
        List<ThinkingLikeCount> likeCounts = thinkingLikeMapper.getCountGroupByThinkingId();
        for (ThinkingLikeCount likeCount : likeCounts) {
            Long count = thinkingLikeCountMapper.getOneByThinkingId(likeCount.getThinkingId());
            if (count != null) { // 更新记录
                thinkingLikeCountMapper.updateByThinkingId(likeCount);
            } else {
                thinkingLikeCountMapper.insert(likeCount);
            }
        }
        Set<String> keys = stringRedisTemplate.keys(RedisConstants.THINK_LIKE_COUNT + "*");
        if (keys != null && !keys.isEmpty())
            stringRedisTemplate.delete(keys);
    }

}
